/**
 * 学习历史管理
 */

class HistoryManager {
    constructor() {
        this.currentFilter = {
            timeRange: 'all', // all, today, week, month
            mode: 'all' // all, dictation, recitation
        };
        console.log('📊 学习历史管理器已加载');
    }

    /**
     * 渲染历史列表页面
     */
    render() {
        const container = document.getElementById('history-list');
        if (!container) return;

        const sessions = this.getHistory(this.currentFilter);
        
        if (sessions.length === 0) {
            container.innerHTML = this.renderEmptyState();
            return;
        }

        // 按日期分组
        const groupedSessions = this.groupByDate(sessions);
        
        let html = '';
        for (const [dateStr, daySessions] of Object.entries(groupedSessions)) {
            html += this.renderDateGroup(dateStr, daySessions);
        }

        container.innerHTML = html;

        // 绑定事件
        this.bindEvents();
    }

    /**
     * 空状态
     */
    renderEmptyState() {
        return `
            <div class="empty-state">
                <div class="empty-icon">📚</div>
                <h3>还没有学习记录</h3>
                <p>开始学习单词，记录将显示在这里</p>
                <button class="btn btn-primary" onclick="app.navigateTo('home')">开始学习</button>
            </div>
        `;
    }

    /**
     * 渲染日期分组
     */
    renderDateGroup(dateStr, sessions) {
        const displayDate = this.formatDateGroup(dateStr);
        
        return `
            <div class="date-group">
                <h3 class="date-header">${displayDate}</h3>
                <div class="sessions-list">
                    ${sessions.map(session => this.renderSessionCard(session)).join('')}
                </div>
            </div>
        `;
    }

    /**
     * 渲染会话卡片
     */
    renderSessionCard(session) {
        const modeIcon = session.mode === 'recitation' ? '📖' : '✍️';
        const modeName = session.mode === 'recitation' ? '背诵模式' : '听写模式';
        const time = new Date(session.startTime).toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });

        const duration = this.formatDuration(session.duration);
        const accuracy = session.stats.accuracy || 0;
        const total = session.stats.total || 0;
        const correct = session.stats.correct || 0;

        // 根据正确率设置颜色
        let accuracyClass = 'accuracy-low';
        if (accuracy >= 90) accuracyClass = 'accuracy-high';
        else if (accuracy >= 70) accuracyClass = 'accuracy-medium';

        return `
            <div class="session-card" data-session-id="${session.id}">
                <div class="session-header">
                    <div class="session-mode">
                        <span class="mode-icon">${modeIcon}</span>
                        <span class="mode-name">${modeName}</span>
                    </div>
                    <div class="session-time">${time}</div>
                </div>
                
                <div class="session-body">
                    <div class="session-wordbook">
                        <span class="wordbook-icon">📚</span>
                        <span class="wordbook-name">${session.wordbookNames.join(', ')}</span>
                    </div>
                    
                    <div class="session-stats">
                        <div class="stat-item">
                            <span class="stat-label">总计</span>
                            <span class="stat-value">${total}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">正确</span>
                            <span class="stat-value stat-correct">${correct}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">用时</span>
                            <span class="stat-value">${duration}</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">正确率</span>
                            <span class="stat-value ${accuracyClass}">${accuracy.toFixed(0)}%</span>
                        </div>
                    </div>
                </div>
                
                <div class="session-footer">
                    <button class="btn-link" onclick="historyManager.showSessionDetail('${session.id}')">
                        查看详情 →
                    </button>
                </div>
            </div>
        `;
    }

    /**
     * 按日期分组
     */
    groupByDate(sessions) {
        const groups = {};
        
        sessions.forEach(session => {
            const date = new Date(session.startTime);
            const dateStr = date.toISOString().split('T')[0]; // YYYY-MM-DD
            
            if (!groups[dateStr]) {
                groups[dateStr] = [];
            }
            groups[dateStr].push(session);
        });

        // 按日期降序排序
        const sortedGroups = {};
        Object.keys(groups)
            .sort((a, b) => b.localeCompare(a))
            .forEach(key => {
                sortedGroups[key] = groups[key];
            });

        return sortedGroups;
    }

    /**
     * 格式化日期分组标题
     */
    formatDateGroup(dateStr) {
        const date = new Date(dateStr);
        const today = new Date();
        const yesterday = new Date(today);
        yesterday.setDate(yesterday.getDate() - 1);

        const dateOnly = (d) => d.toISOString().split('T')[0];

        if (dateOnly(date) === dateOnly(today)) {
            return '今天';
        } else if (dateOnly(date) === dateOnly(yesterday)) {
            return '昨天';
        } else {
            return date.toLocaleDateString('zh-CN', {
                month: 'long',
                day: 'numeric',
                weekday: 'short'
            });
        }
    }

    /**
     * 格式化时长
     */
    formatDuration(ms) {
        const seconds = Math.floor(ms / 1000);
        const minutes = Math.floor(seconds / 60);
        const hours = Math.floor(minutes / 60);

        if (hours > 0) {
            return `${hours}小时${minutes % 60}分`;
        } else if (minutes > 0) {
            return `${minutes}分${seconds % 60}秒`;
        } else {
            return `${seconds}秒`;
        }
    }

    /**
     * 获取历史记录（带过滤）
     */
    getHistory(filter = {}) {
        const allSessions = storageManager.get(storageManager.keys.SESSIONS) || [];
        
        let filtered = allSessions;

        // 时间范围过滤
        if (filter.timeRange && filter.timeRange !== 'all') {
            filtered = this.filterByTimeRange(filtered, filter.timeRange);
        }

        // 模式过滤
        if (filter.mode && filter.mode !== 'all') {
            filtered = filtered.filter(s => s.mode === filter.mode);
        }

        // 按开始时间降序排序
        filtered.sort((a, b) => new Date(b.startTime) - new Date(a.startTime));

        return filtered;
    }

    /**
     * 按时间范围过滤
     */
    filterByTimeRange(sessions, range) {
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        
        return sessions.filter(session => {
            const sessionDate = new Date(session.startTime);
            
            switch (range) {
                case 'today':
                    return sessionDate >= today;
                
                case 'week':
                    const weekAgo = new Date(today);
                    weekAgo.setDate(weekAgo.getDate() - 7);
                    return sessionDate >= weekAgo;
                
                case 'month':
                    const monthAgo = new Date(today);
                    monthAgo.setMonth(monthAgo.getMonth() - 1);
                    return sessionDate >= monthAgo;
                
                default:
                    return true;
            }
        });
    }

    /**
     * 应用过滤器
     */
    applyFilter(timeRange, mode) {
        this.currentFilter = { timeRange, mode };
        this.render();
    }

    /**
     * 显示会话详情
     */
    showSessionDetail(sessionId) {
        const sessions = storageManager.get(storageManager.keys.SESSIONS) || [];
        const session = sessions.find(s => s.id === sessionId);
        
        if (!session) {
            alert('找不到该学习记录');
            return;
        }

        // 创建模态框
        this.showDetailModal(session);
    }

    /**
     * 显示详情模态框
     */
    showDetailModal(session) {
        const modal = document.createElement('div');
        modal.className = 'modal-overlay';
        modal.innerHTML = `
            <div class="modal-content modal-large">
                <div class="modal-header">
                    <h2>学习详情</h2>
                    <button class="btn-close" onclick="this.closest('.modal-overlay').remove()">×</button>
                </div>
                
                <div class="modal-body">
                    ${this.renderSessionDetail(session)}
                </div>
                
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="this.closest('.modal-overlay').remove()">关闭</button>
                </div>
            </div>
        `;

        document.body.appendChild(modal);

        // 点击背景关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.remove();
            }
        });
    }

    /**
     * 渲染会话详情
     */
    renderSessionDetail(session) {
        const modeIcon = session.mode === 'recitation' ? '📖' : '✍️';
        const modeName = session.mode === 'recitation' ? '背诵模式' : '听写模式';
        const startTime = new Date(session.startTime).toLocaleString('zh-CN');
        const duration = this.formatDuration(session.duration);
        
        const stats = session.stats;
        const accuracy = stats.accuracy || 0;

        let detailContent = '';

        if (session.mode === 'dictation') {
            // 听写模式详情
            const dictationType = session.dictationType || 'word';
            const typeNames = {
                word: '单词模式',
                camelCase: '驼峰命名模式',
                fillIn: '填空模式'
            };

            detailContent = `
                <div class="detail-section">
                    <h3>听写详情</h3>
                    <div class="detail-grid">
                        <div class="detail-item">
                            <span class="detail-label">听写类型</span>
                            <span class="detail-value">${typeNames[dictationType] || dictationType}</span>
                        </div>
                    </div>
                </div>

                ${this.renderWordResults(session.results, 'dictation')}
            `;
        } else {
            // 背诵模式详情
            const remember = stats.remember || 0;
            const vague = stats.vague || 0;
            const uncertain = stats.uncertain || 0;

            detailContent = `
                <div class="detail-section">
                    <h3>评估统计</h3>
                    <div class="assessment-stats">
                        <div class="assessment-item assessment-remember">
                            <div class="assessment-icon">✅</div>
                            <div class="assessment-label">记住</div>
                            <div class="assessment-count">${remember}</div>
                        </div>
                        <div class="assessment-item assessment-vague">
                            <div class="assessment-icon">🤔</div>
                            <div class="assessment-label">模糊</div>
                            <div class="assessment-count">${vague}</div>
                        </div>
                        <div class="assessment-item assessment-uncertain">
                            <div class="assessment-icon">❌</div>
                            <div class="assessment-label">不确定</div>
                            <div class="assessment-count">${uncertain}</div>
                        </div>
                    </div>
                </div>

                ${this.renderWordResults(session.results, 'recitation')}
            `;
        }

        return `
            <div class="session-detail">
                <div class="detail-header">
                    <div class="detail-mode">
                        <span class="mode-icon-large">${modeIcon}</span>
                        <div>
                            <h3>${modeName}</h3>
                            <p class="detail-time">${startTime}</p>
                        </div>
                    </div>
                </div>

                <div class="detail-summary">
                    <div class="summary-item">
                        <span class="summary-label">单词本</span>
                        <span class="summary-value">${session.wordbookNames.join(', ')}</span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label">学习时长</span>
                        <span class="summary-value">${duration}</span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label">总计单词</span>
                        <span class="summary-value">${stats.total || 0}</span>
                    </div>
                    ${session.mode === 'dictation' ? `
                        <div class="summary-item">
                            <span class="summary-label">正确数</span>
                            <span class="summary-value summary-correct">${stats.correct || 0}</span>
                        </div>
                        <div class="summary-item">
                            <span class="summary-label">错误数</span>
                            <span class="summary-value summary-wrong">${stats.wrong || 0}</span>
                        </div>
                        <div class="summary-item">
                            <span class="summary-label">正确率</span>
                            <span class="summary-value summary-accuracy">${accuracy.toFixed(1)}%</span>
                        </div>
                    ` : ''}
                </div>

                ${detailContent}
            </div>
        `;
    }

    /**
     * 渲染单词结果列表
     */
    renderWordResults(results, mode) {
        if (!results || results.length === 0) {
            return '<p class="text-muted">无详细记录</p>';
        }

        let html = `
            <div class="detail-section">
                <h3>详细记录</h3>
                <div class="word-results">
        `;

        results.forEach((result, index) => {
            if (mode === 'dictation') {
                const statusIcon = result.correct ? '✅' : '❌';
                const statusClass = result.correct ? 'result-correct' : 'result-wrong';
                
                html += `
                    <div class="result-item ${statusClass}">
                        <div class="result-number">${index + 1}</div>
                        <div class="result-word">
                            <div class="word-text">${result.word}</div>
                            <div class="word-translation">${result.translation || ''}</div>
                        </div>
                        <div class="result-status">
                            <span class="status-icon">${statusIcon}</span>
                            ${!result.correct && result.userAnswer ? `
                                <div class="user-answer">你的答案: ${result.userAnswer}</div>
                            ` : ''}
                        </div>
                    </div>
                `;
            } else {
                // 背诵模式
                const statusIcons = {
                    remember: '✅',
                    vague: '🤔',
                    uncertain: '❌'
                };
                const statusNames = {
                    remember: '记住',
                    vague: '模糊',
                    uncertain: '不确定'
                };
                const statusIcon = statusIcons[result.status] || '❓';
                const statusName = statusNames[result.status] || result.status;
                const statusClass = `result-${result.status}`;

                html += `
                    <div class="result-item ${statusClass}">
                        <div class="result-number">${index + 1}</div>
                        <div class="result-word">
                            <div class="word-text">${result.word}</div>
                            <div class="word-translation">${result.translation || ''}</div>
                        </div>
                        <div class="result-status">
                            <span class="status-icon">${statusIcon}</span>
                            <span class="status-text">${statusName}</span>
                        </div>
                    </div>
                `;
            }
        });

        html += `
                </div>
            </div>
        `;

        return html;
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 这里可以添加其他事件绑定
    }

    /**
     * 删除会话
     */
    deleteSession(sessionId) {
        if (!confirm('确定要删除这条学习记录吗？')) {
            return;
        }

        const sessions = storageManager.get(storageManager.keys.SESSIONS) || [];
        const filtered = sessions.filter(s => s.id !== sessionId);
        storageManager.set(storageManager.keys.SESSIONS, filtered);
        
        this.render();
        this.updateStats();
    }

    /**
     * 清空历史记录
     */
    clearHistory() {
        if (!confirm('确定要清空所有学习记录吗？此操作不可恢复！')) {
            return;
        }

        storageManager.set(storageManager.keys.SESSIONS, []);
        this.render();
        this.updateStats();
    }

    /**
     * 更新统计数据
     */
    updateStats() {
        const sessions = this.getHistory(this.currentFilter);
        const stats = this.calculateStats(sessions);

        // 更新页面上的统计显示
        this.updateStatsDisplay(stats);
    }

    /**
     * 计算统计数据
     */
    calculateStats(sessions) {
        if (sessions.length === 0) {
            return {
                totalSessions: 0,
                totalWords: 0,
                totalTime: 0,
                avgAccuracy: 0,
                dictationSessions: 0,
                recitationSessions: 0
            };
        }

        const stats = {
            totalSessions: sessions.length,
            totalWords: 0,
            totalTime: 0,
            totalCorrect: 0,
            totalAttempts: 0,
            dictationSessions: 0,
            recitationSessions: 0
        };

        sessions.forEach(session => {
            stats.totalWords += session.stats.total || 0;
            stats.totalTime += session.duration || 0;
            
            if (session.mode === 'dictation') {
                stats.dictationSessions++;
                stats.totalCorrect += session.stats.correct || 0;
                stats.totalAttempts += session.stats.total || 0;
            } else {
                stats.recitationSessions++;
            }
        });

        stats.avgAccuracy = stats.totalAttempts > 0 
            ? (stats.totalCorrect / stats.totalAttempts * 100) 
            : 0;

        return stats;
    }

    /**
     * 更新统计显示
     */
    updateStatsDisplay(stats) {
        const elements = {
            totalSessions: document.getElementById('stat-total-sessions'),
            totalWords: document.getElementById('stat-total-words'),
            totalTime: document.getElementById('stat-total-time'),
            avgAccuracy: document.getElementById('stat-avg-accuracy'),
            dictationSessions: document.getElementById('stat-dictation-sessions'),
            recitationSessions: document.getElementById('stat-recitation-sessions')
        };

        if (elements.totalSessions) {
            elements.totalSessions.textContent = stats.totalSessions;
        }
        if (elements.totalWords) {
            elements.totalWords.textContent = stats.totalWords;
        }
        if (elements.totalTime) {
            elements.totalTime.textContent = this.formatDuration(stats.totalTime);
        }
        if (elements.avgAccuracy) {
            elements.avgAccuracy.textContent = stats.avgAccuracy.toFixed(1) + '%';
        }
        if (elements.dictationSessions) {
            elements.dictationSessions.textContent = stats.dictationSessions;
        }
        if (elements.recitationSessions) {
            elements.recitationSessions.textContent = stats.recitationSessions;
        }
    }

    /**
     * 导出学习历史
     */
    exportHistory() {
        const sessions = storageManager.get(storageManager.keys.SESSIONS) || [];
        
        if (sessions.length === 0) {
            alert('没有学习记录可导出');
            return;
        }

        const data = {
            exportDate: new Date().toISOString(),
            totalSessions: sessions.length,
            sessions: sessions
        };

        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `learning-history-${Date.now()}.json`;
        a.click();
        URL.revokeObjectURL(url);
    }

    /**
     * 获取今日学习统计
     */
    getTodayStats() {
        const todaySessions = this.filterByTimeRange(
            storageManager.get(storageManager.keys.SESSIONS) || [],
            'today'
        );

        return this.calculateStats(todaySessions);
    }
}

// 全局实例
const historyManager = new HistoryManager();
window.historyManager = historyManager;

